package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//全局过滤器,对所有请求都会生效
@Component
//@Order(0)
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //获取请求
        ServerHttpRequest request = exchange.getRequest();

        //接收到请求判断是否需要效验身份  获取原始路径 getpath
        String path = request.getURI().getPath();
        if (path.contains("/login/login_auth")){
            //是登录请求继续放心
            return  chain.filter(exchange);
        }
        //通过请求头获取token
        List<String> list = request.getHeaders().get("token");
        if (CollectionUtils.isEmpty(list)){
            //效验身份失败返回401
            //设置响应码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应码
            return response.setComplete();
        }
        //获取token
        String token = list.get(0);
        //效验token是否被篡改 或者过期
                //getClaimsBody载荷
        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);
            if (claims == null){
            }
            int status = AppJwtUtil.verifyToken(claims);
            if (1 == status || 2 == status){
                //token过期或者被篡改
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //必须指定类型
            Long id = claims.get("id",Long.class);
            //mutate建造者模式 idLong类型转换为String类型
            //添加请求头userId
            ServerHttpRequest userId = request.mutate().header("userId", id.toString()).build();
            //让request生效AuthFilter
            exchange.mutate().request(userId);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //执行业务代码

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
